import React, { Component } from 'react';
import App from 'layout/App.js'
import { FormControl, Button, Table, Select, Dropdown, Tree, Icon , Modal, Checkbox} from 'tinper-bee';
import {
    queryOrgListDispatch,
    queryAllRole,
    organizationDistribute,
    organizationUndistributeAll,
    addRole
} from './OrganizationalAssign.js';
import {vendorsDanger as danger ,vendorsWarning as waring } from '../../utils/config.js';
import './index.less';
import CommonModal from './../../components/CommonModal/index.jsx';
import Affix from 'bee-affix';
import moment from 'moment';
moment.locale('zh-cn');
const TreeNode = Tree.TreeNode;
let checkedArrayNoSubChange = [];//角色checkbox选上但是没有提交的数据
let rootData = {};
let allOrgScodeData = [];
let  getOrgDispatchListResp = [];
let  getOrgUndispatchListResp= [];

export default class OrganizationalAssign extends Component {
    constructor (props){
        super(props);
        this.state ={
            showModal:false,
            showOrganizationalModal:false,
            checkedArray: [],
            getDistributeRoleList:[],
            queryAllUndistributeRole:[],
            getAllRole:[],
            getOrgDispatchList:[],
            getOrgUndispatchList:[],
            getOrgAllList:{},
            getOrgAllChildrenList:[],
            getOrgRootDispatchList:[],
            disabled:[],
            expandedKeys:[],
            autoExpandParent:true,
            defaultExpandedKeys:  [],
            defaultCheckedKeys: [],
            checkedKeys:[],
            checkedArrayNoSub:[],
            roleId:'',
            getOrgAllChildren:[],
            defaultSelectedKeys:[],
            selectedKeys:[],
            showUsetepModal:false,
            index:null,
            pkRoleOfDeleteOrg:null,
            record:null,
            handleNode:"",
            value: '',
            pkRoleDistribute:null,
            index:'',
            indexInValue:'',
            indexSearchAll:[]

        }
    }
    componentDidMount () {
        this.init();
    }
    /*组织列表*/
    columslistDisOrg = () =>{
        let _me = this;
        const columnsOraDis = [
            {
                title: "已关联",
                dataIndex: "sname",
                key: "sname",
                textAlign:"left",
                width:"30%"
            },
            {
                title: "",
                dataIndex: "scode",
                key: "scode",
                textAlign:"left",
                width:"30%"
            },
            {
                title: "操作",
                dataIndex: "click",
                key: "click",
                width:"15%",
                render(text, record, index) {
                    return (
                        <div style={{position: 'relative'}} title={text} >
                            <a
                                href="#"
                                tooltip={text}
                                onClick={() => {
                                    _me.setState({
                                        showUsetepModal:true,
                                        record:record,
                                        handleNode:"取消关联"
                                    });
                                }}
                                style={{
                                    textAlign:"left",
                                    paddingRight:38,
                                    color:"#2C7EDC"
                                }}
                            >
                                取消关联
                            </a>
                        </div>
                    )
                }
            }
        ];
        return columnsOraDis;
    }

    confirmCancelConcatForEach = () =>{
        let _me =this;
        let {getOrgDispatchList,record} = _me.state;
        let deleteData = {};
        let isTenantFlag = false;
        for(let getOrgDispatchListIndex=getOrgDispatchList.length-1 ; getOrgDispatchListIndex > 0; getOrgDispatchListIndex-- ){
            if(getOrgDispatchList[getOrgDispatchListIndex]["isTenant"]!==undefined){
                isTenantFlag =true;
                break;
            }
        }
        deleteData={
            pkOrganization:record.pkOrganization,
            pkRole:_me.state.roleId,
            isDistributed:false
        }
        if(record.isTenant){

            deleteData.isTenant='Y';

        }else {
            deleteData.isTenant='N';
        }
        _me.submitOrg(deleteData);

        //当根节点存在的时候，不可以删除其他节点，只可以删除根节点
        /*if(isTenantFlag){
            if(record.isTenant){

                deleteData={
                    pkOrganization:record.pkOrganization,
                    pkRole:_me.state.roleId,
                    isTenant:'Y',
                    isDistributed:false
                }
                _me.submitOrg(deleteData);
            }else {
                waring({ 'text': "租户存在的情况下不可以删除旗下的任何一个组织！"})
                return;
            }
        }else {
            deleteData={
                pkOrganization:record.pkOrganization,
                pkRole:_me.state.roleId,
                isTenant:'N',
                isDistributed:false
            }
            _me.submitOrg(deleteData);
        }*/
    }

    /*角色列表*/
    columnslistFun =() =>{
        let _me = this;
        let columnslist = [

            {   title: "角色名称",
                dataIndex: "roleName",
                key: "roleName",
                width:"35%",
                render(text, record, index) {
                    return (
                        <a style={{position: 'relative'}} title={text} >
                            <div
                                href="#"
                                tooltip={text}
                                onClick={() => _me.showOrganiData(record.roleId)}
                                style={{
                                    textAlign:"left",
                                    paddingRight:38,
                                    color:"#2C7EDC"
                                }}
                            >
                                {text}
                            </div>

                        </a>
                    );
                }
            },
            {   title: "角色编码",
                dataIndex: "roleCode",
                key: "roleCode",
                width:"35%",
                render(text, record, index) {
                    return (
                        <a style={{position: 'relative'}} title={text} >
                            <div
                                href="#"
                                tooltip={text}
                                onClick={() => _me.showOrganiData(record.roleId)}
                                style={{
                                    textAlign:"left",
                                    paddingRight:38,
                                    color:"#2C7EDC"
                                }}
                            >
                                {text}
                            </div>

                        </a>
                    );
                }
            },
            {
                title: "操作",
                dataIndex: "c",
                key: "e",
                render(text, record, index) {
                    return (
                        <div style={{position: 'relative'}} title={text} >
                            <a
                                href="#"
                                tooltip={text}
                                onClick={() => {
                                    _me.setState({
                                        pkRoleDistribute:record.pkRoleDistribute
                                    },()=>{
                                        _me.showOrganiModal(record.roleId)
                                    });

                                }}
                                style={{
                                    textAlign:"left",
                                    paddingRight:38,
                                    color:"#2C7EDC"
                                }}
                            >
                                关联组织
                            </a>
                            <a
                                href="#"
                                tooltip={text}
                                onClick={() => {
                                    /*_me.state.getDistributeRoleList[index].isDistributed=false;
                                    _me.state.getDistributeRoleList.splice(index,1);
                                    _me.setState({
                                        getDistributeRoleList:_me.state.getDistributeRoleList
                                    },()=>{
                                        _me.state.getDistributeRoleList.length!==0 ?
                                        _me.showOrganiData(_me.state.getDistributeRoleList[0].roleId) :

                                            _me.setState({
                                                getOrgDispatchList:[],
                                                getOrgUndispatchList:[],
                                                getOrgAllChildrenList:[]
                                            })

                                    });*/
                                    _me.setState({
                                        showUsetepModal:true,
                                        index:index,
                                        pkRoleOfDeleteOrg:record.roleId
                                    });


                                }}
                                style={{
                                    textAlign:"left",
                                    paddingRight:38,
                                    color:"#2C7EDC"
                                }}
                            >
                                删除
                            </a>
                        </div>
                    );
                }
            }
        ];
        return columnslist;
    }

    init = () => {
        let _me= this;
        queryAllRole({
            'isAjax': 1,
            ieStamp: new Date().getTime()
        }).then(function (response) {
            if (response.data.resultCode != 'busi_ex') {
                for(let index in response.data.result){
                    if(response.data.result[index].isDistributed){
                        _me.setState({
                            getDistributeRoleList:_me.state.getDistributeRoleList.concat(response.data.result[index])
                        });
                    }else {
                        _me.setState({
                            queryAllUndistributeRole:_me.state.queryAllUndistributeRole.concat(response.data.result[index])
                        });
                    }
                }

                _me.setState({
                    getAllRole: [...response.data.result],
                    checkedArray:new Array(response.data.result.length),
                },()=>{
                    JSON.stringify(_me.state.getDistributeRoleList)!==JSON.stringify([])?
                        _me.showOrganiData(_me.state.getDistributeRoleList[0].roleId): null;
                });
            } else {
                danger({ 'text': response.data.exMsg});
            }
        });
    }

    selectRole = () =>{
        this.setState({
            showModal:true
        });
    }

    deleteAllOrgForRole = () =>{
        let _me =this;
        let {pkRoleOfDeleteOrg,index} = _me.state;
        organizationUndistributeAll({
            'isAjax': 1,
            ieStamp: new Date().getTime(),
            pkRole:pkRoleOfDeleteOrg,
        }).then(function (response) {
            if (response.data.resultCode != 'busi_ex') {
                _me.state.getDistributeRoleList[index].isDistributed=false;
                _me.state.getDistributeRoleList.splice(index,1);
                _me.setState({
                    getDistributeRoleList:_me.state.getDistributeRoleList,
                },()=>{
                    _me.state.getDistributeRoleList.length!==0 ?
                        _me.showOrganiData(_me.state.getDistributeRoleList[0].roleId) :

                        _me.setState({
                            getOrgDispatchList:[],
                            getOrgUndispatchList:[],
                            getOrgAllChildrenList:[],

                        })

                });


            } else {
                danger({ 'text': response.data.exMsg});
            }
        });
    }

    closeModal = (params) =>{
        let tempGetAllRole = this.state.getAllRole;
        if(params){
            for(let index=0;index< params.length;index++){
                for(let indexRole=index;indexRole< tempGetAllRole.length;indexRole++){
                    if(params[index].roleId === tempGetAllRole[indexRole].roleId){
                        tempGetAllRole[indexRole].isDistributed=false;
                    }
                }
            }
            this.setState({
                getAllRole:tempGetAllRole
            });

        }
        this.setState({
            showModal:false,
            checkedArray:[],
            showOrganizationalModal:false,
            value:''
        });
    }

    handleChildren =(params, arr)=>{
        let _me = this;
        getOrgDispatchListResp=  _me.state.getOrgDispatchList;
        getOrgUndispatchListResp=  _me.state.getOrgUndispatchList;

        for(let index in params){
            if(params[index].isDistributed){

                getOrgDispatchListResp.push(params[index]);
            }else {
                getOrgUndispatchListResp.push(params[index]);
            }
            allOrgScodeData.push(params[index].scode);
        }

        params.forEach((item, index)=>{
            arr.push(item);
            if(item.children) {
                this.handleChildren(item.children, arr);
            }
        })


    }

    /*查询组织*/
    showOrganiData = (roleId,params) =>{
        let _me = this;
        allOrgScodeData= [];//查询数据
        _me.setState({
            getOrgDispatchList:[],
            getOrgUndispatchList:[],
            roleId:roleId
        });
        queryOrgListDispatch({
            "isAjax":1,
            ieStamp: new Date().getTime(),
            pkRole:roleId,
        }).then(function (response) {
            // console.log(JSON.stringify(response.data.result))
           /* response.data.result = {"changeFlag":null,"dr":0,"assignInfo":null,"pkOrganization":null,"pkSrc":null,"pkFinanceOrg":null,"pkGroup":null,"pkParent":null,"pkTenant":"x61tnmfx","scode":"xue0jjr0jambn1dp","sname":"工程云测试","innerCode":null,"isLastVersion":null,"enableState":null,"startDate":null,"endDate":null,"creator":null,"creationtime":null,"modifier":null,"modifytime":null,"children":[{"changeFlag":null,"dr":0,"assignInfo":null,"pkOrganization":"01372e24-2055-4a5e-a480-7d69a1f46acb","pkSrc":"00013A10000000000A1X","pkFinanceOrg":null,"pkGroup":null,"pkParent":null,"pkTenant":null,"scode":"0911","sname":"0911","innerCode":null,"isLastVersion":null,"enableState":null,"startDate":null,"endDate":null,"creator":null,"creationtime":null,"modifier":null,"modifytime":null,"children":null,"isDistributed":null,"tenantName":null,"tenantCode":null},
                    {"changeFlag":null,"dr":0,"assignInfo":null,"pkOrganization":"1ef22fa8-1019-42fd-a4d5-0ac2c1ec25a6","pkSrc":"0001ZP10000000005AM0","pkFinanceOrg":null,"pkGroup":null,"pkParent":null,"pkTenant":null,"scode":"091105","sname":"091105","innerCode":null,"isLastVersion":null,"enableState":null,"startDate":null,"endDate":null,"creator":null,"creationtime":null,"modifier":null,"modifytime":null,"children":null,"isDistributed":null,"tenantName":null,"tenantCode":null},
                    {"changeFlag":null,"dr":0,"assignInfo":null,"pkOrganization":"08d534a5-e012-4027-a72b-2484b5c6f964","pkSrc":"0001ZP10000000005AMD","pkFinanceOrg":null,"pkGroup":null,"pkParent":null,"pkTenant":null,"scode":"091107","sname":"091107","innerCode":null,"isLastVersion":null,"enableState":null,"startDate":null,"endDate":null,"creator":null,"creationtime":null,"modifier":null,"modifytime":null,"children":null,"isDistributed":null,"tenantName":null,"tenantCode":null},
                    {"changeFlag":null,"dr":0,"assignInfo":null,"pkOrganization":"60cfc1f1-824c-4694-b43a-503985947e9f","pkSrc":"00013A10000000000A1X","pkFinanceOrg":null,"pkGroup":null,"pkParent":null,"pkTenant":null,"scode":"0911768","sname":"0911768","innerCode":null,"isLastVersion":null,"enableState":null,"startDate":null,"endDate":null,"creator":null,"creationtime":null,"modifier":null,"modifytime":null,"children":null,"isDistributed":null,"tenantName":null,"tenantCode":null},
                    {"changeFlag":null,"dr":0,"assignInfo":null,"pkOrganization":"60cfc1f1-824c-4694-b43a-503985947e9f","pkSrc":"00013A10000000000A1X","pkFinanceOrg":null,"pkGroup":null,"pkParent":null,"pkTenant":null,"scode":"09117s68","sname":"09117s68","innerCode":null,"isLastVersion":null,"enableState":null,"startDate":null,"endDate":null,"creator":null,"creationtime":null,"modifier":null,"modifytime":null,"children":null,"isDistributed":null,"tenantName":null,"tenantCode":null},
                    {"changeFlag":null,"dr":0,"assignInfo":null,"pkOrganization":"60cfc1f1-824c-4694-b43a-503985947e9f","pkSrc":"00013A10000000000A1X","pkFinanceOrg":null,"pkGroup":null,"pkParent":null,"pkTenant":null,"scode":"091e1768","sname":"091e1768","innerCode":null,"isLastVersion":null,"enableState":null,"startDate":null,"endDate":null,"creator":null,"creationtime":null,"modifier":null,"modifytime":null,"children":null,"isDistributed":null,"tenantName":null,"tenantCode":null},
                    {"changeFlag":null,"dr":0,"assignInfo":null,"pkOrganization":"60cfc1f1-824c-4694-b43a-503985947e9f","pkSrc":"00013A10000000000A1X","pkFinanceOrg":null,"pkGroup":null,"pkParent":null,"pkTenant":null,"scode":"09151768","sname":"09151768","innerCode":null,"isLastVersion":null,"enableState":null,"startDate":null,"endDate":null,"creator":null,"creationtime":null,"modifier":null,"modifytime":null,"children":null,"isDistributed":null,"tenantName":null,"tenantCode":null},
                    {"changeFlag":null,"dr":0,"assignInfo":null,"pkOrganization":"60cfc1f1-824c-4694-b43a-503985947e9f","pkSrc":"00013A10000000000A1X","pkFinanceOrg":null,"pkGroup":null,"pkParent":null,"pkTenant":null,"scode":"091e12768","sname":"091e12768","innerCode":null,"isLastVersion":null,"enableState":null,"startDate":null,"endDate":null,"creator":null,"creationtime":null,"modifier":null,"modifytime":null,"children":null,"isDistributed":null,"tenantName":null,"tenantCode":null},
                    {"changeFlag":null,"dr":0,"assignInfo":null,"pkOrganization":"60cfc1f1-824c-4694-b43a-503985947e9f","pkSrc":"00013A10000000000A1X","pkFinanceOrg":null,"pkGroup":null,"pkParent":null,"pkTenant":null,"scode":"0911w768","sname":"0911w768","innerCode":null,"isLastVersion":null,"enableState":null,"startDate":null,"endDate":null,"creator":null,"creationtime":null,"modifier":null,"modifytime":null,"children":null,"isDistributed":null,"tenantName":null,"tenantCode":null},
                    {"changeFlag":null,"dr":0,"assignInfo":null,"pkOrganization":"60cfc1f1-824c-4694-b43a-503985947e9f","pkSrc":"00013A10000000000A1X","pkFinanceOrg":null,"pkGroup":null,"pkParent":null,"pkTenant":null,"scode":"0915we1768","sname":"0915we1768","innerCode":null,"isLastVersion":null,"enableState":null,"startDate":null,"endDate":null,"creator":null,"creationtime":null,"modifier":null,"modifytime":null,"children":null,"isDistributed":null,"tenantName":null,"tenantCode":null},
                    {"changeFlag":null,"dr":0,"assignInfo":null,"pkOrganization":"60cfc1f1-824c-4694-b43a-503985947e9f","pkSrc":"00013A10000000000A1X","pkFinanceOrg":null,"pkGroup":null,"pkParent":null,"pkTenant":null,"scode":"0911i7e68","sname":"0911i7e68","innerCode":null,"isLastVersion":null,"enableState":null,"startDate":null,"endDate":null,"creator":null,"creationtime":null,"modifier":null,"modifytime":null,"children":null,"isDistributed":null,"tenantName":null,"tenantCode":null},
                    {"changeFlag":null,"dr":0,"assignInfo":null,"pkOrganization":"60cfc1f1-824c-4694-b43a-503985947e9f","pkSrc":"00013A10000000000A1X","pkFinanceOrg":null,"pkGroup":null,"pkParent":null,"pkTenant":null,"scode":"0911w7680","sname":"0911w7680","innerCode":null,"isLastVersion":null,"enableState":null,"startDate":null,"endDate":null,"creator":null,"creationtime":null,"modifier":null,"modifytime":null,"children":null,"isDistributed":null,"tenantName":null,"tenantCode":null},
                    {"changeFlag":null,"dr":0,"assignInfo":null,"pkOrganization":"60cfc1f1-824c-4694-b43a-503985947e9f","pkSrc":"00013A10000000000A1X","pkFinanceOrg":null,"pkGroup":null,"pkParent":null,"pkTenant":null,"scode":"091r1768","sname":"091r1768","innerCode":null,"isLastVersion":null,"enableState":null,"startDate":null,"endDate":null,"creator":null,"creationtime":null,"modifier":null,"modifytime":null,"children":null,"isDistributed":null,"tenantName":null,"tenantCode":null},
                    {"changeFlag":null,"dr":0,"assignInfo":null,"pkOrganization":"60cfc1f1-824c-4694-b43a-503985947e9f","pkSrc":"00013A10000000000A1X","pkFinanceOrg":null,"pkGroup":null,"pkParent":null,"pkTenant":null,"scode":"09117g68","sname":"09117g68","innerCode":null,"isLastVersion":null,"enableState":null,"startDate":null,"endDate":null,"creator":null,"creationtime":null,"modifier":null,"modifytime":null,"children":null,"isDistributed":null,"tenantName":null,"tenantCode":null},
                    {"changeFlag":null,"dr":0,"assignInfo":null,"pkOrganization":"60cfc1f1-824c-4694-b43a-503985947e9f","pkSrc":"00013A10000000000A1X","pkFinanceOrg":null,"pkGroup":null,"pkParent":null,"pkTenant":null,"scode":"091h1768","sname":"091h1768","innerCode":null,"isLastVersion":null,"enableState":null,"startDate":null,"endDate":null,"creator":null,"creationtime":null,"modifier":null,"modifytime":null,"children":null,"isDistributed":null,"tenantName":null,"tenantCode":null},
                    {"changeFlag":null,"dr":0,"assignInfo":null,"pkOrganization":"60cfc1f1-824c-4694-b43a-503985947e9f","pkSrc":"00013A10000000000A1X","pkFinanceOrg":null,"pkGroup":null,"pkParent":null,"pkTenant":null,"scode":"09s768","sname":"09s768","innerCode":null,"isLastVersion":null,"enableState":null,"startDate":null,"endDate":null,"creator":null,"creationtime":null,"modifier":null,"modifytime":null,"children":null,"isDistributed":null,"tenantName":null,"tenantCode":null},
                    {"changeFlag":null,"dr":0,"assignInfo":null,"pkOrganization":"b0120f31-59f9-4466-b16f-45983cad7974","pkSrc":"00013A10000000000A1X","pkFinanceOrg":null,"pkGroup":null,"pkParent":null,"pkTenant":null,"scode":"0912","sname":"0912","innerCode":null,"isLastVersion":null,"enableState":null,"startDate":null,"endDate":null,"creator":null,"creationtime":null,"modifier":null,"modifytime":null,"children":null,"isDistributed":null,"tenantName":null,"tenantCode":null},
                    {"changeFlag":null,"dr":0,"assignInfo":null,"pkOrganization":"2725c8f0-e2f8-4180-b978-f17a6244e94b","pkSrc":"0001ZP10000000005ANB","pkFinanceOrg":null,"pkGroup":null,"pkParent":null,"pkTenant":null,"scode":"091202","sname":"091202","innerCode":null,"isLastVersion":null,"enableState":null,"startDate":null,"endDate":null,"creator":null,"creationtime":null,"modifier":null,"modifytime":null,"children":null,"isDistributed":null,"tenantName":null,"tenantCode":null},
                    {"changeFlag":null,"dr":0,"assignInfo":null,"pkOrganization":"d1f78891-c30c-4d5f-8e0e-2e634db93d08","pkSrc":"0001ZP10000000005ANO","pkFinanceOrg":null,"pkGroup":null,"pkParent":null,"pkTenant":null,"scode":"091203","sname":"091203","innerCode":null,"isLastVersion":null,"enableState":null,"startDate":null,"endDate":null,"creator":null,"creationtime":null,"modifier":null,"modifytime":null,"children":[
                            {"changeFlag":null,"dr":0,"assignInfo":null,"pkOrganization":"04d236e6-94ec-404f-af94-5be5b77accce","pkSrc":"0001ZP10000000005C4S","pkFinanceOrg":null,"pkGroup":null,"pkParent":"0001ZP10000000005ANO","pkTenant":null,"scode":"091204","sname":"091204","innerCode":null,"isLastVersion":null,"enableState":null,"startDate":null,"endDate":null,"creator":null,"creationtime":null,"modifier":null,"modifytime":null,"children":null,"isDistributed":null,"tenantName":null,"tenantCode":null},
                            {"changeFlag":null,"dr":0,"assignInfo":null,"pkOrganization":"6988e5f2-b229-4dd5-9c68-1c04738a17c8","pkSrc":"0001ZP10000000005C4W","pkFinanceOrg":null,"pkGroup":null,"pkParent":"0001ZP10000000005ANO","pkTenant":null,"scode":"091205","sname":"091205","innerCode":null,"isLastVersion":null,"enableState":null,"startDate":null,"endDate":null,"creator":null,"creationtime":null,"modifier":null,"modifytime":null,"children":null,"isDistributed":null,"tenantName":null,"tenantCode":null}],
                        "isDistributed":null,"tenantName":null,"tenantCode":null}],
                "isDistributed":false,"tenantName":"工程云测试","tenantCode":"xue0jjr0jambn1dp"}*/
             if (response.data.resultCode != 'busi_ex') {
            let arr = [];
            rootData = {
                pkOrganization:   response.data.result.pkOrganization,
                pkTenant:  response.data.result.pkTenant,
                isDistributed:  response.data.result.isDistributed,
                tenantName: response.data.result.tenantName,
                tenantCode: response.data.result.tenantCode,
                sname: response.data.result.sname,
                scode: response.data.result.scode,
                isTenant:'Y'
            };
            _me.handleChildren(response.data.result.children, arr);
            if( response.data.result.isDistributed){
                getOrgDispatchListResp.unshift(rootData);
            }else {
                getOrgUndispatchListResp.unshift(rootData);
            }
            _me.setState({
                getOrgDispatchList:getOrgDispatchListResp,
                getOrgUndispatchList: getOrgUndispatchListResp,
                getOrgAllChildrenList:response.data.result.children,
                getOrgAllChildren:arr,
                getOrgAllList:response.data.result
            },()=>{
                if(params){
                    let defaultExpandedKeys = [];
                    let defaultCheckedKeys = [];
                    for(let index in _me.state.getOrgAllChildren){
                        defaultExpandedKeys.push(_me.state.getOrgAllChildren[index].scode);
                        if(_me.state.getOrgAllChildren[index].isDistributed){
                            defaultCheckedKeys.push(_me.state.getOrgAllChildren[index].scode);
                        }
                    }
                    if(rootData .isDistributed){
                        defaultCheckedKeys.push(rootData.tenantCode);
                    }
                    _me.setState({
                        showOrganizationalModal:true,
                        defaultExpandedKeys:defaultExpandedKeys,
                        defaultCheckedKeys:defaultCheckedKeys,
                        checkedKeys:defaultCheckedKeys,
                        roleId:roleId,
                        pkRoleDistribute:_me.state.pkRoleDistribute
                    });
                }
            });



              } else {
                  danger({ 'text': response.data.exMsg });
              }
        });

    }

    showOrganiModal = (roleId) =>{
        this.showOrganiData(roleId,true);
    }
    /*角色checkbox的操作 */
    onCheckboxChange = (text, record, index) => {
        let self = this;
        let {getAllRole} = self.state;
        let checkedArray = getAllRole.concat();

        checkedArray[index].isDistributed = !getAllRole[index].isDistributed;
        if( checkedArray[index].isDistributed ){
            checkedArrayNoSubChange.splice(0,0,checkedArray[index]) ;
        }
    };
    /*角色checkBox处理*/
    renderColumnsMultiSelect(columns) {
        let defaultColumns = [
            {
                key: "checkbox",
                dataIndex: "checkbox",
                width: "5%",
                render: (text, record, index) => {
                    return (
                        <Checkbox
                            disabled={record.isDistributed?true:false}
                            className="table-checkbox"
                            checked={record.isDistributed}
                            onChange={()=>this.onCheckboxChange(text, record, index)}
                        />
                    );
                }
            }
        ];
        columns = defaultColumns.concat(columns);
        return columns;
    }
    /*角色提交*/
    submit = () =>{
        this.closeModal();
        let _me= this;
        let {getAllRole}=_me.state;
        let checkedArrayOfData = [];//角色最后提交的数据

        for(let index in getAllRole){
            if(getAllRole[index].isDistributed){
                checkedArrayOfData.splice(0,0,getAllRole[index]);
            }
        }
        let pkRoleArray=[];
        for(let i =0;i< checkedArrayNoSubChange.length;i++){
            pkRoleArray.push(checkedArrayNoSubChange[i].roleId);
        }
        pkRoleArray.toString() ?
            addRole({
                "isAjax":1,
                ieStamp: new Date().getTime(),
                pkRoles:pkRoleArray
            }).then(function (response) {
                if(response.data.resultCode != 'busi_ex'){
                    for(let index in response.data.result){
                        checkedArrayOfData[index].pkRoleDistribute= response.data.result[index].pkRoleDistribute;
                    }
                    _me.setState({
                        getDistributeRoleList :[...checkedArrayOfData.reverse()]
                    },()=>{
                        checkedArrayNoSubChange = [];
                        _me.showOrganiData(checkedArrayOfData[0].roleId)

                    });
                }else {
                    danger({"text":response.data.msg});
                }
            }): _me.setState({
                showModal:false
            });

    }


    getUndistributeRoleList = () =>{

        const columnsList = [
            {
                title: "",
                dataIndex: "roleCode",
                key: "roleCodeUn",
                width: 100
            },
            {
                title: "",
                dataIndex: "roleName",
                key: "roleNameUn",
                width: 100
            },
        ];
        return columnsList;
    }
    /*组织提交*/
    submitOrg =(params)=>{
        let _me =this;
        let { roleId, getOrgDispatchList,getOrgAllList,getOrgAllChildrenList ,getOrgAllChildren , checkedKeys, pkRoleDistribute } = _me.state;
        let orgSubmitData = [];//最后提交组织的数据
        let checkedKeysTemp = [];//选中数据临时数据

        if(params === "submitOrg"){
            /*找到默认的数据里是否有被改变的*/
            let checkedKeysIsChecked = checkedKeys.checked?checkedKeys.checked:checkedKeys;
            for(let index in checkedKeysIsChecked){

                checkedKeysTemp.push(checkedKeysIsChecked[index]);

                for(let dispatchListIndex in getOrgDispatchList){
                    if(getOrgDispatchList[dispatchListIndex].scode === checkedKeysIsChecked[index]){
                        checkedKeysTemp.splice(0,1);
                        break;
                    }
                }
            }
            for(let i in getOrgDispatchList){
                if(checkedKeysIsChecked.indexOf(getOrgDispatchList[i].scode) === -1){
                    checkedKeysTemp.splice(0,0,getOrgDispatchList[i].scode);
                }
            }

            for(let indexchecked in checkedKeysTemp){
                for(let indexOrg in getOrgAllChildren){

                    if(checkedKeysTemp[indexchecked] === getOrgAllChildren[indexOrg].scode){
                        if(getOrgAllChildren[indexOrg].isDistributed){
                            getOrgAllChildren[indexOrg].isDistributed = false;
                        }else {
                            getOrgAllChildren[indexOrg].isDistributed=true;
                        }
                        orgSubmitData.push({
                            pkOrganization:getOrgAllChildren[indexOrg].pkOrganization,
                            pkRole:roleId,
                            isTenant:'N',
                            isDistributed:getOrgAllChildren[indexOrg].isDistributed,
                            pkSrc :getOrgAllChildren[indexOrg].pkSrc,
                            pkRoleDistribute:pkRoleDistribute
                        });

                        break;
                    }
                }

            }
            if(getOrgAllList.isDistributed && checkedKeysIsChecked.indexOf(getOrgAllList.tenantCode) === -1){
                getOrgAllList.isDistributed = false;
                orgSubmitData.push({
                    pkOrganization:getOrgAllList.pkOrganization,
                    pkRole:roleId,
                    isTenant:'Y',
                    isDistributed:getOrgAllList.isDistributed,
                    pkSrc :getOrgAllList.pkSrc,
                    pkRoleDistribute:pkRoleDistribute
                });
            }
            if(!getOrgAllList.isDistributed && checkedKeysIsChecked.indexOf(getOrgAllList.tenantCode) !== -1){
                getOrgAllList.isDistributed = true;
                orgSubmitData.push({
                    pkOrganization:getOrgAllList.pkOrganization,
                    pkRole:roleId,
                    isTenant:'Y',
                    isDistributed:getOrgAllList.isDistributed,
                    pkSrc :getOrgAllList.pkSrc,
                    pkRoleDistribute:pkRoleDistribute
                });
            }

        }else {
            orgSubmitData.push(params);
        }
        orgSubmitData ?
            organizationDistribute({
                "isAjax":1,
                ieStamp: new Date().getTime(),
                orgAndRoleVOS:orgSubmitData
            }).then(function (response) {
                if (response.data.resultCode != 'busi_ex') {
                    _me.setState({
                        showOrganizationalModal:false,
                        handleNode:"",
                        record:null
                    });
                    /*查询组织接口*/
                    _me.showOrganiData(roleId);

                } else {
                    danger({ 'text': response.data.exMsg });
                }
            }) :
            _me.setState({
                showOrganizationalModal:false
            });
    }
    /*组织checkbox的操作 */
    onCheck = (checkedKeys) => {
        let self = this;
        let {getOrgAllChildren} = self.state;
        let cks = {};

        cks = {
            checked: checkedKeys.checked || checkedKeys,
        };
        self.setState({
            checkedKeys:cks,
        });


        /*当租户（根节点）是可以控制全选的时候的代码   留用*/
        /* let checkedLength = self.state.checkedKeys.length !==undefined ?self.state.checkedKeys.length:self.state.checkedKeys.checked.length;

         if(checkedKeys.indexOf(rootData.scode) === -1 && checkedKeys.length===getOrgAllChildren.length){
             if( checkedKeys.length===getOrgAllChildren.length && checkedLength <= checkedKeys.length){
                 checkedKeys.push(rootData.scode);
                 cks = {
                     checked: checkedKeys
                 };
             }else {

                 cks = {
                     checked: checkedKeys
                 };
             }

         }else if(checkedKeys.indexOf(rootData.scode) !== -1 ){
             for(let checkedKeysI in checkedKeys){
                 if(checkedKeys[checkedKeysI] === rootData.scode){
                     checkedKeys.splice(checkedKeysI,1);
                 }
             }
             for(let allOrgScodeDataI in allOrgScodeData){
                 if(checkedKeys.indexOf(allOrgScodeData[allOrgScodeDataI])=== -1){
                     checkedKeys.push(allOrgScodeData[allOrgScodeDataI]);
                 }
             }
             checkedKeys.push(rootData.scode);
             cks = {
                 checked: checkedKeys
             };
             if(checkedKeys.indexOf(rootData.scode) === -1 && checkedKeys.length===getOrgAllChildren.length){
                 cks = {
                     checked: checkedKeys
                 };
             }


         }else {
             cks = {
                 checked: checkedKeys.checked || checkedKeys,
             };
         }*/

        cks = {
            checked: checkedKeys.checked || checkedKeys,
        };
        self.setState({
            checkedKeys:cks,
        });
    }
    onSelect = (param) =>{
        let _me =this;
        let selectedKeysTemp = _me.state.checkedKeys;
        if(selectedKeysTemp.checked){
            selectedKeysTemp = selectedKeysTemp.checked;
        }
        if(param.toString()===""){
            return
        }
        if(selectedKeysTemp!==[]){
            if(selectedKeysTemp.lastIndexOf(param.toString())===-1){
                selectedKeysTemp.push(param.toString());
            }else {
                let index = selectedKeysTemp.indexOf(param.toString());
                selectedKeysTemp.splice(index,1);
            }
        }else {
            selectedKeysTemp=[];
        }

        _me.setState({
            checkedKeys:selectedKeysTemp
        });
        this.onCheck(selectedKeysTemp);

    }
    goBack = () =>{
        window.history.back();
    }

    onConfirm = () =>{

        if(this.state.handleNode === "取消关联"){
            this.confirmCancelConcatForEach();
        }else {
            this.deleteAllOrgForRole();
        }
        this.setState({
            showUsetepModal:false,
        });
    }
    hideCommonModal = () =>{
        this.setState({
            showUsetepModal:false
        });
    }

    onChange = (value) => {

        this.setState({
            value: value.currentTarget.value,
        });
    }
    /*搜索的树定位*/
    scrollToAnchor = (index, indexInValue,indexSearchAll) => {
         if(indexInValue!==-1){
             if(index!==undefined){
                 indexSearchAll.push(index+1);
             }
        }
        if(indexInValue!==-1){
            if(index===undefined){
                setTimeout(()=>{
                    document.getElementsByClassName("u-tree-title")[0].scrollIntoView();
                },0);
            }else {
                setTimeout(()=>{
                    document.getElementsByClassName("u-tree-title")[indexSearchAll[0]].scrollIntoView();
                },0);
            }
        }

    }
    search = (item,index,indexSearchAll) =>{
        if(item===undefined){
            return;
        }
        let title=item;
        const indexInValue = this.state.value?title.indexOf(this.state.value):-1;
        const beforeStr = item.substr(0, indexInValue);
        const afterStr = this.state.value?item.substr(indexInValue + this.state.value.length):item;

        title = title.indexOf(this.state.value)>-1 ? (
            <span>
                {beforeStr}
                <span className="u-tree-searchable-filter">{this.state.value}</span>
                {afterStr}
                </span>
        ) : <span>{item}</span>;
        this.scrollToAnchor(index, indexInValue,indexSearchAll);
        return title;
    }

    handlerGetSearchData=(indexSearchAll)=>{
        let {getOrgAllChildren,value}=this.state;
        if(rootData.sname.indexOf(value)>-1){
            this.scrollToAnchor(undefined, 1,indexSearchAll);
        }else {
            let title='';
            for(let i= 0; i< getOrgAllChildren.length; i++){
                title=getOrgAllChildren[i].sname;
                const indexInValue = value?title.indexOf(this.state.value):-1;
                const beforeStr = getOrgAllChildren[i].sname.substr(0, indexInValue);
                const afterStr = value?getOrgAllChildren[i].sname.substr(indexInValue + value.length):getOrgAllChildren[i].sname;

                title = title.indexOf(this.state.value)>-1 ? (
                    <span>
                {beforeStr}
                        <span className="u-tree-searchable-filter">{value}</span>
                        {afterStr}
                </span>
                ) : <span>{getOrgAllChildren[i].sname}</span>;
                this.scrollToAnchor(i, indexInValue,indexSearchAll);
            }
            return title;

        }


    }
    render (){
        let columns = this.renderColumnsMultiSelect(this.getUndistributeRoleList());
        let indexSearchAll= [];
        let { showModal,
            showOrganizationalModal,
            getDistributeRoleList,
            getAllRole,
            getOrgDispatchList,
            getOrgAllList,
            getOrgAllChildrenList,
            defaultExpandedKeys,
            defaultCheckedKeys,
            checkedKeys,
            showUsetepModal,
            handleNode,
            defaultSelectedKeys,
            selectedKeys,
            value
        } = this.state;

        const loop = data => data.map((item,index) => {
            let titleSearch = this.search(item.sname,index,indexSearchAll);

            if (item.children){
                return (
                    <TreeNode key={item.scode}
                              title={titleSearch}
                    >
                        {item.children? loop(item.children) : null }
                    </TreeNode>
                )
            }

            return <TreeNode    key={item.scode} title={titleSearch}/>  ;

        });

        return (
            <App>
                <CommonModal show={showUsetepModal}
                             cancel={this.hideCommonModal}
                             confirm={this.onConfirm}
                             content={handleNode?"是否取消已关联的组织？":"是否删除所有已关联的组织？"}
                             backdrop={false}
                             hide={this.hideCommonModal}
                />
                <Affix>
                    <div style={{background:'rgb(238, 238, 238)'}}>
                        <div className="headerTitle">
                            <div className="title">
                                <h4>组织权限</h4>
                            </div>
                            <Button className="goBack" onClick={this.goBack}>返回</Button>
                        </div>
                        <div className="product_container">
                            <div className="header clearfix" ref="fixedTop">
                                <h1 className="fl">角色选择</h1>
                                <Button colors="primary" className="fr btn" onClick={this.selectRole}>选择角色</Button>
                            </div>
                        </div>
                    </div>
                </Affix>

                {getDistributeRoleList ?
                    <Table
                        columns={this.columnslistFun()}
                        data={getDistributeRoleList}
                        scroll={{y:360}}
                        useFixedHeader={true}
                        bordered={true}
                        className={"u-table-header"}
                        emptyText={()=>"暂时没有数据！"}
                        style={{width:"40%",zIndex:9,top:150,marginLeft:30,position:"fixed",}}
                    />: null
                }

                {getDistributeRoleList&&getOrgDispatchList ?
                    <Table
                        columns={this.columslistDisOrg()}
                        data={getOrgDispatchList}
                        scroll={{y:360}}
                        useFixedHeader={true}
                        bordered={true}
                        className={"u-table-header"}
                        emptyText={()=>"暂时没有数据！"}
                        style={{width:"40%",zIndex:9,top:150,marginLeft:"56%",position:"fixed",}}
                    />: null
                }

                {/*角色*/}
                <Modal
                    show={showModal}
                    onHide={()=>this.closeModal(checkedArrayNoSubChange)}
                    backdrop={false}
                    style={{ width:500, top: 100, height:500}}
                >
                    <Modal.Header
                        closeButton={true}
                    >
                        <Modal.Title>选择角色</Modal.Title>
                    </Modal.Header>
                    <Modal.Body>
                        <Table
                            columns={columns}
                            data={getAllRole}
                            scroll={{y:250}}
                            useFixedHeader={true}
                            showHeader={false}
                            emptyText={()=>"暂时没有数据！"}
                            title={currentData => <div className="u-table-title">角色列表</div>}
                            style={{backgroundColor:"#eee"}}
                        />
                    </Modal.Body>
                    <Modal.Footer
                        className="text-center"
                    >
                        <Button
                            style={{width:340,height:40}}
                            colors="primary"
                            onClick={()=>this.submit()}
                        >确认</Button>
                    </Modal.Footer>
                </Modal>

                {/*组织*/}
                <Modal
                    show={showOrganizationalModal}
                    onHide={this.closeModal}
                    backdrop={false}
                    style={{ width:500, top: 100, height:500}}
                    className='tree-containers'
                >
                    <div className='modal_content'>
                        <Modal.Header
                            closeButton={true}
                        >
                            <Modal.Title>选择组织</Modal.Title>
                        </Modal.Header>
                        <div className='Modal_Body'>
                            <Modal.Body>
                                <div className='center_bottom'>
                                    <div className="search-group clearfix">
                                        <FormControl size="lg"
                                                     className='search_form'
                                                     placeholder={`输入名称`}
                                                     onChange={this.onChange}
                                                     showClose={true}
                                                     componentClass={"input"}
                                                     value={value}
                                        />
                                        <a href="javascript:;" className="search-btn" onClick={()=>this.handlerGetSearchData(indexSearchAll)}></a>
                                    </div>
                                    <Tree
                                        showLine={true}
                                        checkable={true}
                                        checkStrictly={true}
                                        checkedKeys={checkedKeys}
                                        defaultExpandedKeys={defaultExpandedKeys}
                                        defaultCheckedKeys = {defaultCheckedKeys}
                                        onCheck={this.onCheck}
                                        defaultSelectedKeys={defaultSelectedKeys}
                                        selectedKeys={selectedKeys}
                                        onSelect={this.onSelect}
                                    >
                                        <TreeNode
                                            key={getOrgAllList.tenantCode}
                                            title={<span>{this.search(getOrgAllList.tenantName)}</span>}
                                        >
                                            {loop(getOrgAllChildrenList)}
                                        </TreeNode>
                                    </Tree>
                                </div>

                            </Modal.Body>
                        </div>
                        <Modal.Footer
                            className="text-center"
                        >
                            <Button
                                style={{width:340,height:40}}
                                colors="primary"
                                onClick={() => this.submitOrg("submitOrg")}
                            >确认</Button>
                        </Modal.Footer>
                    </div>
                </Modal>
            </App>
        )
    }
}